#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: serializer.py
@contact: zwb15083976291@163.com
@time: 2022/02/21
"""
import datetime

from django.db.models import Sum

from common.filters import FrontEndArticlesTagFilter
from common.models import BlogUser, BlogWebInfo, BlogPages, BlogArticle, BlogMusics, BlogCategorie, BlogTag, BlogVisits
from common.serializers.serializer import UserSerializer, BlogWebInfoSerializer, PageConfigSerializer, \
    FrontEndArticlesPaginatorSerializer, FrontEndArticleSerializer, FrontEndArticleListSerializer, MusicsListSerializer
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.views import BaseGenericAPIView, BasePaginateGenericAPIView
# 必须放在最后，不知道什么原因导致循环问题
from rest_framework.generics import GenericAPIView


# 前台网站信息
class WebsiteInfoView(BaseGenericAPIView):
    serializer_class = UserSerializer

    def get(self, request):
        visits_count = BlogVisits.objects.aggregate(Sum('visits_count')).get("visits_count__sum", 0)
        count_info = dict(article_count=BlogArticle.objects.filter(articles_status=0).count(),
                          categorie_count=BlogCategorie.objects.count(),
                          tag_count=BlogTag.objects.count(),
                          visits_count=visits_count)
        return CommonResponse(data=dict(blogInfo=self.serializer_class(BlogUser.objects.get(pk=1)).data,
                                        webInfo=BlogWebInfoSerializer(BlogWebInfo.objects.get(pk=1)).data,
                                        countInfo=count_info))


# 前台页面配置视图
class WebsitePageConfigView(BaseGenericAPIView):

    def get(self, request):
        # 添加访问量
        self.add_visits()
        background = {item['page_name']: item['background_image_url'] for item in
                      PageConfigSerializer(BlogPages.objects.all(), many=True).data}
        return CommonResponse(data=dict(background=background))

    def add_visits(self):
        data = datetime.datetime.now().date()
        current_obj = BlogVisits.objects.filter(visits_date=data).first()
        if current_obj:
            current_obj.visits_count += 1
            current_obj.save()
        else:
            BlogVisits.objects.create(**dict(visits_date=data))


# 前台文章列表视图
class ArticleListView(BasePaginateGenericAPIView):
    diff_methods_serializer_class = dict(get=FrontEndArticlesPaginatorSerializer)
    diff_methods_request_params = dict(
        get=dict(optional=['pageNum', 'pageSize', 'categorie', 'tag'],
                 defualt_value=dict(pageNum=1, pageSize=5)), )
    filter_backends = [FrontEndArticlesTagFilter]

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        query_set = self.filter_queryset(
            queryset=BlogArticle.objects.filter(articles_status=0).order_by('-articles_is_topping', '-create_time'))
        paginator, models = self.paginate_queryset(query_set, self.serializer.validated_data)
        return CommonResponse(data=self.get_paginated_response(self.serializer.validated_data, paginator,
                                                               FrontEndArticleListSerializer(instance=models,
                                                                                             many=True).data))


# 前台音乐接口
class MusicsListView(GenericAPIView):

    def get(self, request):
        musics = BlogMusics.objects.all()
        serial_fields = ['id', 'music_cover', 'music_artist', 'music_name', 'music_url']
        data = MusicsListSerializer(serial_fields=serial_fields, instance=musics, many=True).data
        return CommonResponse(data=data)
